package darknet.core.impl.net;

import darknet.core.spec.net.Message;
import darknet.core.spec.net.ProtocolHandler;
import darknet.core.spec.net.StreamableMessage;
import java.io.IOException;

/**
 * Implementation of Protocol Handler for Base application.
 * 
 * @author Yoyo
 */
class BaseProtocolHandler implements ProtocolHandler {

    /** Base protocol */
    private BaseProtocol protocol = BaseProtocol.getCurrent();

    /** Base application */
    private BaseApplicationImpl application;

    /**
     * Initialise a new base protocol handler.
     * 
     * @param application
     */
    public BaseProtocolHandler(BaseApplicationImpl application) {
        
        if (application == null) {
            throw new IllegalArgumentException("application is null");
        }
        this.application = application;
    }

    @Override
    public boolean canHandle(Message toHand) {

        if (toHand == null) {
            throw new IllegalArgumentException("toHand is null");
        }

        return protocol.equals(toHand.getHeader().getProtocol());
    }

    @Override
    public void handle(StreamableMessage toHand) {

        if (toHand == null) {
            throw new IllegalArgumentException("toHand is null");
        }

        handleMessage(toHand);

    }

    private void handleMessage(StreamableMessage toHand) {

        if (toHand.getWrapped() instanceof PingMessage) {

            handlePingMessage(toHand);

        }
    }

    private void handlePingMessage(StreamableMessage toHand) {

        // Close the connection.
        try {
            toHand.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
